<?php

/*
 * C活动功能模块
 * 功能：活动
 */

namespace User\Controller;

use Think\C_Controller;

class ActionController extends C_Controller {

    public function __construct() {
        parent::__construct();
        $this->store_id = (int) $_GET['store_id'];
        if ($this->store_id < 1) {
            //throw new \Exception();
            $this->shopList();
        }
        $s = new \Home\Logic\StoreLogic();
        $store = $s->getStore($this->store_id);
        $this->assign('logo', $store['logo']);
        $this->assign('store_name', $store['name']);
        $this->assign('store',$store);
    }

    public function index() {
        layout('layout2');
        $a = new \Home\Logic\ActionLogic();
        $o = new \Home\Logic\OrderLogic();
        if(!$_SESSION['barber_id']){
            $_SESSION['barber_id']= 0;
        }
        $actions = $a->getActionList($this->store_id,$_SESSION['barber_id'], 0);
        foreach ($actions as $k => $v) {
            $re = $o->getActionOrderNumByActon($v['id']);
            $actions[$k]['num'] = (int) $re['num'];
            //活动图
            $ids = json_decode($v['content'], true);
            if ($ids['ids']) {
                $img=array();
                $item = new \Home\Logic\ShopitemLogic();
                $items = $item->getItemsByIds(array_keys($ids['ids']), $v['store_id'], true);
                if(count($items[0]['images'])>0){
                    if(count($items[0]['images'])>1){
                        $img[] = $items[0]['images'][0]['image'];
                        $img[] = $items[0]['images'][1]['image'];
                    }else{
                        $img[] = $items[0]['images'][0]['image'];
                        $img[] = '/upload/action.jpg';
                    }   
                }else{
                    $img[] = '/upload/action.jpg';
                    $img[] = '/upload/action.jpg';
                }
                $actions[$k]['img'] =$img; 
            }
        }
        $this->assign('actions', $actions);
        $this->display('action');
    }

    public function append() {
        $start = (int) $_GET['start'];
        $a = new \Home\Logic\ActionLogic();
        $o = new \Home\Logic\OrderLogic();
        if(!$_SESSION['barber_id']){
            $_SESSION['barber_id']=0;
        }
        $actions = $a->getActionList($this->store_id,$_SESSION['barber_id'], $start);
        foreach ($actions as $k => $v) {
            $re = $o->getActionOrderNumByActon($v['id']);
            $actions[$k]['num'] = (int) $re['num'];
            //活动图
            $ids = json_decode($v['content'], true);
            if ($ids['ids']) {
                $img=array();
                $item = new \Home\Logic\ShopitemLogic();
                $items = $item->getItemsByIds(array_keys($ids['ids']), $v['store_id'], true);
                if(count($items[0]['images'])>0){
                    if(count($items[0]['images'])>1){
                        $img[] = $items[0]['images'][0]['image'];
                        $img[] = $items[0]['images'][1]['image'];
                    }else{
                        $img[] = $items[0]['images'][0]['image'];
                        $img[] = '/upload/action.jpg';
                    }   
                }else{
                    $img[] = '/upload/action.jpg';
                    $img[] = '/upload/action.jpg';
                }
                $actions[$k]['img'] =$img; 
            }
        }
        if (count($actions) < 1) {
            exit('false');
        } else {
            exit(json_encode($actions));
        }
    }
    
    public function info() {

        $_SESSION['s_verify'] = time();
        $this->setSession($_SESSION);
        $this->foo(json_encode($_SESSION));
        //获取open_id
       /*import('Api2', 'weixin');
       $api = new \Weixin\Api2();
       $this->app_id = WEIXIN_PAY_APP_ID;
       $this->app_secret = WEIXIN_PAY_SECRET;
       $api->getUserToken('system', $this->app_id, $this->app_secret, true);
       $wx_user = $api->getUserInfo($this->app_id, $this->app_secret);
       $name = $wx_user['nickname'];
       $sex = $wx_user['sex'];
       $photo = $wx_user['headimgurl'];
       $this->assign('name', $name);
       $this->assign('sex', $sex - 1);
       $this->assign('photo', $photo);*/
        //获取open_id over
        $aid = (int) $_GET['aid'];
        $a = new \Home\Logic\ActionLogic();
        $action = $a->getAction($aid);
        if ($action['id'] < 1 || $action['status'] != $a::RELEASE_STATUS) {
            exit; //直接拒绝非法用户
        }
        if ($action['store_id'] != $this->store_id) {
            exit; //直接拒绝非法用户
        }

        $ids = json_decode($action['content'], true);
        if ($ids['ids']) { //为兼容老版活动，做兼容，特此判断
            $item = new \Home\Logic\ShopitemLogic();
            $ids_keys = array_keys($ids['ids']);
            $items = $item->getItemsByIds($ids_keys, $action['store_id'], true);
            $action['price'] = $ids_keys[0];
            foreach ($items as $k => $v) {//获取套餐详情（包含的单品）
                if ($v['is_meal_set'] == 1) {//如果是套餐，则取出包含的单品
                    $meal_set_items = $item->getItemByMealSetId($v['id'], $action['store_id'], true);
                    $items[$k]['old_price'] = 0;
                    $items[$k]['old_price'] += $v['price'];
                }else{
                    $items[$k]['old_price'] += $v['price'];
                }
                $items[$k]['meal_set_items'] = $meal_set_items;
            }
            $this->assign('items', $items);

        }

        $o = new \Home\Logic\OrderLogic();

        $s = new \Home\Logic\StoreLogic();
        $store = $s->getStore($this->store_id);

        //微信分享
        $api = import('Api2', 'Weixin');
        $api = new \Weixin\Api2();
        $data['jsapi_ticket'] = $api->getTicket(WEIXIN_PAY_APP_ID, WEIXIN_PAY_SECRET);
        $data['noncestr'] = 'fewgasfgadussfeko'; //临时写死
        $data['timestamp'] = time();
        $data['url'] = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        ksort( $data );
        foreach ($data as $k => $v) {
            $str .= $k . '=' . $v . '&';
        }
        $data['sign'] = sha1(substr($str, 0, -1));
        if (strstr($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')) {
            $this->assign('weixin', true);
        }

        //发型师信息
        $barber_id = $action['barber_id'] > 0 ? $action['barber_id'] : (int) $_GET['barber_id'];
        if ($barber_id > 0) {
            $b = new \Home\Logic\BarberLogic();
            $barber = $b->getBarber($barber_id);
            $this->assign('barber', $barber);
        }

        //团单人员列表
        if ($_GET['team_number']) {
            $mt = new \Home\Logic\OrderLogic();
            if ($action['price'] > 0) {
                if($action['model_type']==1){
                    //拼团
                    $count = $mt->getPayOrderCount(trim($_GET['team_number']));
                }
                if ($count != false) {
                    $this->assign('team', $count['team']);
                    $this->assign('count', $count['count']);
                }
            } else {
                $count = $mt->getTeamCount(trim($_GET['team_number']));
                if ($count > 0) {
                    $team = $mt->getTeam(trim($_GET['team_number']));
                    $this->assign('team', $team);
                    $this->assign('count', $count);
                }
            }
		$this->assign('team_number',trim($_GET['team_number']));
        }
        $this->assign('data', $data );
        $this->assign('store', $store);
        $this->assign('action', $action);
        $this->assign('verify', $_SESSION['s_verify']);
        if ($action['model_type'] == 2)
        {
            $this->display('detail');
        }
        else if ($action['model_type'] == 3 )
        {   
            //公益 团单人员列表
            $mt = new \Home\Logic\OrderLogic();
            $count = $mt->getPayOrderCountByAid($aid);
            if ($count != false) {
                $this->assign('team', $count['team']);
                $this->assign('count', $count['count']);
            }

            // 支付成功后返回 pay_status = ok
            if($count['count']<1){
                $pay_status = 0;
            }else{
                $pay_status = trim( $_GET['pay_status'] )?trim( $_GET['pay_status'] ):0;
            }
            
            // 判断订单状态
            $status = (int)$_GET['status'];
            if($status==1 || $status== 2 ||$status== 4 ){
                $team_number = trim($_GET['team_number']);
                $client_id = $_SESSION['client_id'];
                $team = $mt->getTeamLeader($team_number,$client_id);
                $this->assign('headimg',$team['headimg']);  //微信头像
                $this->assign('nickname',$team['nickname']);    //微信名
            }else{
                $headimg = trim($_GET['headimg']);
                $nickname = trim($_GET['nickname']);
                $this->assign('headimg',$headimg);  //微信头像
                $this->assign('nickname',$nickname);    //微信名
            }
            $this->assign( 'pay_status', $pay_status );
            layout(false);
            $this->display( 'crowdFunding' );
        }
        else
        {
            $this->display('preview');
        }
    }

    public function createqrcode() {
        $api = new \Weixin\Api2();
        $re = $api->createQrcode($this->app_id, $this->app_secret);
    }

    public function createqrcodeWeixin() {
        include_once(APP_PATH . "Weixin/phpqrcode/phpqrcode.php");
        $errorCorrectionLevel = "L"; // 纠错级别：L、M、Q、H  
        $matrixPointSize = "4"; // 点的大小：1到10  
        \QRcode::png($_GET['url'], false, $errorCorrectionLevel, $matrixPointSize);
        exit;
    }

    public function qrcode() {
        layout(false);
        $s = new \Home\Logic\StoreLogic();
        $store = $s->getStore($this->store_id);
        $this->assign('qrcode', $store['code']);
        $this->display('qrcode');
    }

    public function create() {
        $data['name'] = $_POST['name'];
        $data['sex'] = $_POST['sex'];
        $data['mobile'] = $_POST['mobile'];
        $data['action_id'] = $_POST['action_id'];
        $data['image'] = $_POST['image'];
        $code = $_POST['code'];
        import('MsgCode', 'Msgcode');
        $m = new \Msgcode\MsgCode(true);
        if (!$m->checkCode($data['mobile'], $code)) {
            redirect('/user/action/info?&store_id=' . (int) $_GET['store_id'] . '&aid=' . $data['action_id']);
        }
        if (strlen($data['name']) < 0 ||
                strlen($data['image']) < 1) {
            redirect('/user/action/info?&store_id=' . (int) $_GET['store_id'] . '&aid=' . $data['action_id']);
        }
        $data['image'] = str_replace('./', '/', $data['image']);
        $data['score'] = rand(60, 70);
        $a = new \Home\Logic\ActionLogic();
        import('Mongodb');
        $mongo = \Think\Mongodb::create();
        $mongo->selectDatabase('test');
        $mongo->selectCollection('kaka'); 
        if ($data['sex'] == 0) {
            $title =$mongo->findAll();
            $title = $title[0][1];
        } elseif ($data['sex'] == 1) {
            $title =$mongo->findAll();
            $title = $title[0][0];
        }
        $num = rand(0, 9);
        $data['title'] = $title["$num"];
        $data['create_time'] = time();
        $re = $a->insertFace($data);
        if ($re) {
            redirect('/user/action/previewFace?store_id=' . (int) $_GET['store_id'] . '&id=' . $re . '&aid=' . $data['action_id']);
        } else {
            redirect('/error/?Msg=1');
        }
    }

    public function previewFace() {
        layout(false);

        $_SESSION['s_verify'] = time();
        $this->setSession($_SESSION);
        //获取open_id
        import('Api2', 'weixin');
        $api = new \Weixin\Api2();
        $this->app_id = WEIXIN_PAY_APP_ID;
        $this->app_secret = WEIXIN_PAY_SECRET;
        $api->getUserToken('system', $this->app_id, $this->app_secret, true);
        $wx_user = $api->getUserInfo($this->app_id, $this->app_secret);
        $name = $wx_user['nickname'];
        $id = (int) $_GET['id'];
        $store_id = (int) $_GET['store_id'];
        $action_id = (int) $_GET['aid'];
        $a = new \Home\Logic\ActionLogic();
        $re = $a->selectFace($id);
        $percent = $a->percentFace($re['score'], $re['action_id']);
        if ($action_id != $re['action_id']) {
            exit; //直接拒绝非法用户
        }
        $c = new \Home\Logic\CouponLogic();
        $coupon = $c->getHuiByActionId($re['action_id']);
        $s = new \Home\Logic\StoreLogic();
        $store = $s->getStore($store_id);
        import('Mongodb');
        $mongo = \Think\Mongodb::create();
        $mongo->selectDatabase('test');
        $mongo->selectCollection('helps');
        $where=array('id'=>$re['id']);
        $help =$mongo->findAll($where); 
        $mongo->selectCollection('kaka');
        $emotions=$mongo->findAll();
        $emotions = $emotions[0][3];

        (int) $em = ceil(($percent['num'] / $percent['count']) * 100);
        if ($em <= 20) {
            $emotion = $emotions['20'];
        }
        if (20 < $em) {
            if ($em <= 30) {
                $emotion = $emotions['30'];
            }
        }
        if (30 < $em) {
            if ($em <= 40) {
                $emotion = $emotions['40'];
            }
        }
        if (40 < $em) {
            if ($em <= 50) {
                $emotion = $emotions['50'];
            }
        }
        if (50 < $em) {
            if ($em <= 60) {
                $emotion = $emotions['60'];
            }
        }
        if (60 < $em) {
            if ($em <= 70) {
                $emotion = $emotions['70'];
            }
        }
        if (70 < $em) {
            if ($em <= 80) {
                $emotion = $emotions['80'];
            }
        }
        if (80 < $em) {
            if ($em <= 90) {
                $emotion = $emotions['90'];
            }
        }
        if (90 < $em) {
            $emotion = $emotions['100'];
        }

        foreach ($help as $k => $v) {
            if (in_array($name.'-'.$re['id'], $v)) {
                //点过赞
                $this->assign('helped', 1);
            }
        }
        $this->assign('emotion', $emotion);
        $this->assign('name', $name);
        $this->assign('coupon', $coupon);
        $this->assign('help', $help);
        $this->assign('percent', $percent);
        $this->assign('face', $re);
        $this->assign('store', $store);
        $this->assign('action_id', $action_id);
        $_SESSION['s_verify'] = time();
        $this->setSession($_SESSION);
        //微信分享
        $api = import('Api2', 'Weixin');
        $api = new \Weixin\Api2();
        $data['jsapi_ticket'] = $api->getTicket(WEIXIN_PAY_APP_ID, WEIXIN_PAY_SECRET);
        $data['noncestr'] = 'fewgasfgadusswloo'; //临时写死
        $data['timestamp'] = time();
        $data['url'] = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        ksort($data);
        foreach ($data as $k => $v) {
            $str .= $k . '=' . $v . '&';
        }
        $data['sign'] = sha1(substr($str, 0, -1));
        if (strstr($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')) {
            $this->assign('weixin', true);
        }
        $this->assign('data', $data);
        $this->display('previewFace');
    }

    public function coupon() {
        $mobile = $_POST['mobile'];
        $code = (int) $_POST['code'];
        $id = (int) $_POST['id'];
        $data['coupon_id'] = (int) $_POST['coupon_id'];
        $c = new \Home\Logic\CouponLogic();
        $coupon = $c->getHuiById($data['coupon_id']);
        import('MsgCode', 'Msgcode');
        $m = new \Msgcode\MsgCode();
        if (!$m->checkCode($mobile, $code)) {
            redirect('/user/action/previewFace?d=1&store_id=' . (int) $_GET['store_id'] . '&id=' . $id);
        }
        $u = new \Home\Logic\UserLogic();
        $user = $u->getUserByAccount($mobile);
        if ($user == '') {
            $re = $u->createUser($mobile);
            $data['client_id'] = $re;
        } else {
            $data['client_id'] = $user['id'];
        }
        $data['number'] = $this->code();
        $data['create_time'] = time();
        $data['store_id'] = $this->store_id;
        $data['barber_id'] = (int) $_GET['barber_id'];
        if ($id < 1 ||
                $data['store_id'] < 1 ||
                $data['client_id'] < 1 ||
                $data['barber_id'] < 0) {

            redirect('/user/action/previewFace?d=2&store_id=' . $this->store_id . '&id=' . $id . '&barber_id=' . $data['barber_id'] . '&coupon_id=' . $data['coupon_id'] . '&aid=' . $coupon['is_action']);
        }

        //检查是否领取过
        $d = $c->double($data);
        if ($d) {
            redirect('/user/action/previewFace?d=3&store_id=' . $this->store_id . '&coupon_id=' . $data['coupon_id'] . '&barber_id=' . $data['barber_id'] . '&id=' . $id . '&aid=' . $coupon['is_action']); //已领取过
        }
        //领取
        $s = $c->count($data['coupon_id'], $data);
        if ($s == false) {
            redirect('/user/action/previewFace?d=4&store_id=' . $this->store_id . '&coupon_id=' . $data['coupon_id'] . '&barber_id=' . $data['barber_id'] . '&id=' . $id . '&aid=' . $coupon['is_action']); //领取完
        }
        if ($s) {

            $st = new \Home\Logic\StoreLogic();
            $store = $st->getStore($this->store_id);
            $m->sendCoupon($mobile, $store['name'], $coupon['name']);
            redirect('/user/action/previewFace?d=5&store_id=' . $this->store_id . '&coupon_id=' . $data['coupon_id'] . '&barber_id=' . $data['barber_id'] . '&id=' . $id . '&aid=' . $coupon['is_action']);
        }
    }

    //识别码
    function code() {
        return date('ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }

    public function updateFace() {
        $action_id = $_GET['action_id'];
        $id = $_GET['id'];
        $score = $_GET['score'];
        $name = $_GET['name'];
        $a = new \Home\Logic\ActionLogic();
        $re = $a->updateFace($id, $score);
        $face = $a->selectFace($id);
        if ($face['action_id'] != $action_id) {
            redirect('/error');
        }
        $num = rand(0, 5);
        import('Mongodb');
        $mongo = \Think\Mongodb::create();
        $mongo->selectDatabase('test');
        $mongo->selectCollection('kaka');
        $e = $mongo->findAll();
        $e = $e[0][2];
        $evaluate = $e["$num"];
        $evaluate = array($name, $evaluate);
        $mongo->selectCollection('helps');
        $arr = array('id'=>$face['id'],'name'=>$name.'-'.$face['id'],'evaluate'=>$evaluate);
        $result = $mongo->insert($arr);
        if ($face) {
            echo $num;
            exit;
        } else {
            echo 'false';
            exit;
        }
        exit;
    }

    public function foo($str) {
        $f = fopen('./public/upload/g.txt', 'a+');
        fwrite($f, $str . "\r\n");
        fclose($f);
    }


}
